<?php
/*
 * @Author: your name
 * @Date: 2020-11-01 23:52:41
 * @LastEditTime: 2020-12-07 15:27:14
 * @LastEditors: Please set LastEditors
 * @Description: IP处理
 * @FilePath: /special/application/adminapiv3/service/module_manage/netfilter/IpProcessService.php
 */
namespace app\adminapiv3\service\module_manage\netfilter;

class IpProcessService
{
    /**
     * @name: ip数据输入处理
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2020-11-02 00:42:11
     */
    public static function inputProcess ($src_ip, $dest_ip)
    {
        $src_ip_a = self::process($src_ip);
        $dest_ip_a = self::process($dest_ip);
        
        $return = [];
        foreach ($src_ip_a as $sip_v)
        {
            foreach ($dest_ip_a as $dip_v)
            {
                $temp['src_ip_s'] = $sip_v[0];
                $temp['src_ip_e'] = $sip_v[1];
                $temp['dest_ip_s'] = $dip_v[0];
                $temp['dest_ip_e'] = $dip_v[1];

                $return[] = $temp;
            }
        }

        return $return;
    }

    /**
     * @name: 处理
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2020-11-02 01:14:42
     */
    private static function process ($ip)
    {
        $ip = explode(',', strtolower($ip));
        foreach ($ip as $sv)
        {
            $sv_a = explode('-', $sv);
            if (count($sv_a) == 1)
            {
                if ($sv_a[0] == 'any')
                {
                    $sv_a = [
                        0,
                        4294967295
                    ];
                }
                else
                {
                    $sv_a = [
                        ip2long($sv_a[0]),
                        ip2long($sv_a[0])
                    ];
                }
            }
            else
            {
                $sv_a = [
                    ip2long($sv_a[0]),
                    ip2long($sv_a[1])
                ];
            }

            $return[] = $sv_a;
        }

        return $return;
    }

    /**
     * @name: 输出处理
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2020-11-02 10:15:55
     */
    public static function outProcess ($ip_s)
    {
        $ip_a = array_unique(explode(',', $ip_s));
        foreach ($ip_a as $k => $ip)
        {
            $ipa = explode('-', $ip);
            switch ($ipa)
            {
                case $ipa[0] == $ipa[1] :
                    $ip_a[$k] = long2ip($ipa[0]);
                    break;
                case $ipa[0] == 0 && $ipa[1] == 4294967295 :
                    $ip_a[$k] = 'any';
                    break;
                default:
                    $ip_a[$k] = long2ip($ipa[0]) . '-' . long2ip($ipa[1]);
            }

        }
        $ip_s = implode(',', $ip_a);

        return $ip_s;
    }
}
